package com.gp.billsrecord.ui.login

import android.app.Application
import androidx.lifecycle.*
import androidx.room.withTransaction
import com.gp.billsrecord.R
import com.gp.billsrecord.base.BaseViewModel
import com.gp.billsrecord.model.data.LogonUser
import com.gp.billsrecord.model.room.AppDatabase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*

/**
 * 登录的数据逻辑控制
 */
class LoginViewModel(application: Application) : BaseViewModel(application) {

    private val _loginForm = MutableLiveData<LoginFormState>()
    val loginFormState: LiveData<LoginFormState> = _loginForm

    private val _loginResult = MutableLiveData<LoginResult>()
    val loginResult: LiveData<LoginResult> = _loginResult

    private val database = AppDatabase.get(getApplication())

    /**
     * 登录方法
     */
    fun login(nameOrPhone: String, password: String) {
        viewModelScope.launch {
            delay(1000L)
            database.withTransaction {
                //先取信息
                val user = database.logonUserDao().queryNameOrPhone(nameOrPhone)
                user?.also {
                    if (user.userPwd == password) {
                        //存储userId,目的是为了后续的操作都是针对对当前登录的用户
                        updateUserId(user.userId)
                        //把登录信息返回给页面
                        _loginResult.postValue(
                            LoginResult(
                                LoggedInUserView(
                                    user.userName,
                                    user.userId
                                )
                            )
                        )
                    } else {
                        _loginResult.postValue(LoginResult(error = LoginFail.PASSWORD_WRONG))//密码错误
                    }
                }
                    ?: _loginResult.postValue(LoginResult(error = LoginFail.NO_SUCH_USER))//用户不存在，直接返回错误
            }
        }
    }


    /**
     * 检测输入是否符合要求
     */
    fun loginDataChanged(username: String, password: String) {
        if (!isUserNameValid(username)) {
            _loginForm.value = LoginFormState(usernameError = R.string.invalid_username)
        } else if (!isPasswordValid(password)) {
            _loginForm.value = LoginFormState(passwordError = R.string.invalid_password)
        } else {
            _loginForm.value = LoginFormState(isDataValid = true)
        }
    }

    // 验证用户名
    private fun isUserNameValid(username: String?): Boolean {
        return username?.isNotBlank() ?: false
    }

    // 验证密码
    private fun isPasswordValid(password: String): Boolean {
        return password.length >= 5
    }

    /**
     * 注册
     */
    fun registerUser(nameOrPhone: String, password: String) = liveData(Dispatchers.IO) {
        delay(1000L)
        val user = if (nameOrPhone.isPhoneStr()) {
            //name随机一个
            val randomName = UUID.randomUUID().toString().split("-")[0]
            val name = "Name_$randomName"
            LogonUser(name, nameOrPhone, password)
        } else {
            LogonUser(nameOrPhone, null, password)
        }
        val userId = database.logonUserDao().register(user)//将创建的用户信息保存到数据库，并返回ID，失败会返回-1
        updateUserId(userId)
        emit(userId)//把用户ID返回给页面
    }
}

private fun String.isPhoneStr(): Boolean {
    return Regex("^1\\d{10}\$").matches(this)
}
